use crate::{configuration, ApiError, ApiResult, ToError};
use lapin::{Channel, Connection, ConnectionProperties};
use log::info;
use std::sync::LazyLock;

/// 创建数据库连接
async fn get_connect() -> Connection {
    let amqp = configuration::amqp();
    let url = amqp.url();
    let addr: &str = if let Some(url) = url {
        url
    } else {
        let ssl = amqp.ssl();
        let protocol = if ssl { "amqps" } else { "amqp" };
        let username = amqp.username();
        let password = amqp.password();
        let host = amqp.host();
        let port = amqp.port();
        let vhost = amqp.vhost();
        &format!(
            "{}://{}:{}@{}:{}/{}",
            protocol, username, password, host, port, vhost,
        )
    };
    let conn = Connection::connect(&addr, ConnectionProperties::default()).await;
    match conn {
        Ok(conn) => {
            info!("rabbitmq连接成功");
            conn
        },
        Err(e) => panic!("rabbitmq连接失败：{e}")
    }
}

static CONNECT: LazyLock<Connection> =
    LazyLock::new(|| futures_lite::future::block_on(get_connect()));

/// 初始化amqp连接
pub fn init() -> &'static Connection {
    &CONNECT
}
/// 获取amqp通道
pub async fn get() -> ApiResult<Channel>  {
    CONNECT.create_channel().await.to_err(|| ApiError::Biz("创建amqp通道失败".into()))
}
